package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.exception.GoodsCountException;
import com.cskaoyan.market.service.wx.WxCartService;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.CartIndexVo;
import com.cskaoyan.market.vo.WxCartCheckoutVo;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wx/cart")
public class WxCartController {
    @Autowired
    WxCartService wxCartService;
    @Autowired
    SecurityManager securityManager;

    @GetMapping("goodscount")
    public Object goodscount() {
        try {
            SecurityUtils.setSecurityManager(securityManager);
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            MarketUser user = (MarketUser) session.getAttribute("user");
            Integer userId = user.getId();
            Integer data = wxCartService.getTotalCartGoods(userId);
            return ResponseUtil.ok(data);
        }catch (Exception e){
            throw new GoodsCountException();
        }
    }

    @PostMapping("add")
    @RequiresAuthentication
    public Object add(@RequestBody Map<String, Object> map) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        Integer userId = user.getId();
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer goodsId = (Integer) map.get("goodsId");
        short number = NumberUtils.toShort(map.get("number").toString(), (short) 0);
        Integer productId = (Integer) map.get("productId");
        Integer data = wxCartService.addCart(goodsId, number, productId, userId);
        return ResponseUtil.ok(data);
    }

    @GetMapping("index")
    @RequiresAuthentication
    public Object index() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        Integer userId = user.getId();
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        CartIndexVo data = null;
        try {
            data = wxCartService.index(userId);
        } catch (AuthorizationException e) {
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.ok(data);

    }

    @PostMapping("update")
    @RequiresAuthentication
    public Object update(@RequestBody Map<String, Object> requestBody) {
        Integer productId = (Integer) requestBody.get("productId");
        Integer goodsId = (Integer) requestBody.get("goodsId");
        short number = NumberUtils.toShort(requestBody.get("number").toString(), (short) 0);
        Integer id = (Integer) requestBody.get("id");
        boolean result = wxCartService.update(productId, goodsId, number, id);
        if (result) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail(605, "编辑失败");
    }

    @PostMapping("delete")
    @RequiresAuthentication
    public Object delete(@RequestBody Map<String, Object> requestBody) {
        List<Integer> productIds = (ArrayList<Integer>) requestBody.get("productIds");
        CartIndexVo result = wxCartService.delete(productIds, getUserId());
        if (result != null) {
            return ResponseUtil.ok(result);
        }
        return ResponseUtil.fail(606, "删除失败");
    }

    @PostMapping("checked")
    @RequiresAuthentication
    public Object check(@RequestBody Map map) {
        List<Integer> productIds = (ArrayList<Integer>) map.get("productIds");
        Integer checkedNum = (Integer) map.get("isChecked");
        Boolean checked = checkedNum != 0;
        Integer userId = getUserId();
        CartIndexVo wxCartCheckVo = wxCartService.check(productIds, checked, userId);
        return ResponseUtil.ok(wxCartCheckVo);
    }

    @GetMapping("checkout")
    @RequiresAuthentication
    public Object checkout(@RequestParam Integer cartId,
                           @RequestParam Integer addressId,
                           @RequestParam Integer couponId,
                           @RequestParam Integer userCouponId,
                           @RequestParam Integer grouponRulesId) {
        Integer userId = getUserId();
        WxCartCheckoutVo wxCartCheckoutVo = wxCartService.checkout(cartId, addressId, couponId, userCouponId, grouponRulesId, userId);
        return ResponseUtil.ok(wxCartCheckoutVo);
    }

    @PostMapping("fastadd")
    @RequiresAuthentication
    public Object fastadd(@RequestBody Map map) throws IOException {
        Integer goodsId = (Integer) map.get("goodsId");
        short number = NumberUtils.toShort(map.get("number").toString(), (short) 0);
        Integer productId = (Integer) map.get("productId");
        Integer userId = getUserId();
        Map<String, Integer> attributeValueMap = wxCartService.fastadd(goodsId, number, productId, userId);
        return ResponseUtil.ok(attributeValueMap.get("cartId"));
    }

    private Integer getUserId() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        return user.getId();
    }
}
